package com.wys.spring.db;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.core.annotation.AnnotationUtils;

import javax.annotation.Nullable;
import javax.validation.constraints.NotNull;

public class DataSourceInterceptor implements MethodInterceptor {


    @Nullable
    @Override
    public Object invoke(@NotNull MethodInvocation invocation) throws Throwable {
        try {
            DataSource dataSource = AnnotationUtils.findAnnotation(invocation.getMethod(), DataSource.class);
            if (ObjectUtils.isEmpty(dataSource)) {
                dataSource = AnnotationUtils.findAnnotation(invocation.getThis().getClass(),DataSource.class);
            }
            DataSourceHandler.putDataSource(dataSource.name());
            Object obj = invocation
                    .proceed();
            DataSourceHandler.removeDataSource();
            return obj;
        } catch (Exception e) {
            DataSourceHandler.removeDataSource();
            throw e;
        }
    }
}
